package com.hunttown.mes.manage.controller.files;

import com.hunttown.mes.manage.service.files.FileSystemStorageManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @title: 文件存储
 * @author: wangjunfu
 * @date: 2022年11月29日 10:49
 * @description:
 */
@Controller
@RequestMapping(value = "/files/storage")
public class FileSystemStorageController {

    private final FileSystemStorageManageService fileSystemStorageManageService;

    @Autowired
    public FileSystemStorageController(FileSystemStorageManageService fileSystemStorageManageService) {
        this.fileSystemStorageManageService = fileSystemStorageManageService;
    }

    //存储路径，测试写本地
    private final String abPath = "D:\\upload_files";

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "files/index";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String updloadFiles(Model model, @RequestParam("file") MultipartFile file) {

        //文件名
        String filename = file.getOriginalFilename();
        filename = fileSystemStorageManageService.store(file, filename, abPath);

        //model.addAttribute("message", "<a href='/files/storage/downloadFile?filename=" + filename + "' target='_blank'>" + filename + "</a>");

        model.addAttribute("message", "<img src='/files/storage/showFile?filename=" + filename + "' />");

        return "common/empty-modal";
    }

    //下载
    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    public ResponseEntity<Resource> downloadFile(String filename) {
        Resource file = null;

        try {
            file = fileSystemStorageManageService.loadAsResource(filename, abPath);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        if (file != null) {
            return ((ResponseEntity.BodyBuilder) ResponseEntity.ok().header("Content-Disposition", new String[]{"attachment; filename=\"" + filename + "\""})).body(file);
        }

        return null;
    }

    //浏览器直接预览或img中显示
    @RequestMapping(value = "/showFile", method = RequestMethod.GET)
    public void showFile(HttpServletResponse response, String filename) {

        response.setCharacterEncoding("UTF-8");

        try {
            Resource file = fileSystemStorageManageService.loadAsResource(filename, abPath);

            if (file != null) {
                response.reset();
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

                String contentType = "image/png";
                response.setContentType(contentType);

                byte[] buf = new byte[1024];
                InputStream in = file.getInputStream();

                int L;
                while ((L = in.read(buf)) != -1) {
                    toClient.write(buf, 0, L);
                }

                in.close();
                toClient.flush();
                toClient.close();

            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "找不到相关资源");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
